/*

 */

#import "SROTAViewController.h"
#import "UIViewController+More.h"
#import "CARingSDK.h"

@interface SROTAViewController ()<CAOTAProtocal>

@property(assign, nonatomic)BOOL isFInish;

@end

@implementation SROTAViewController

//@synthesize blockSize;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    
    self.textView.text = @"";
    [self.progressView setProgress:0];
    [self.progressTextLabel setText:[NSString stringWithFormat:@"%d%%", 0]];
    

}

- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    
    // start ota
    [CARingSDK instance].bleOtaDelegate = self;
    [[CARingSDK instance] functionStartOta:self.updateImageFileUrl];
}

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    

}

-(void)initUI {
    
    WEAK_SELF
    [self customNavStyleNormal:@"Upgrede" BackBlk:^{
        STRONG_SELF
        if (strongSelf == nil) {
            return;
        }
        if (strongSelf.isFInish) {
            //
            [strongSelf.navigationController popToRootViewControllerAnimated:YES];
        } else {
            [strongSelf showAlertWarningWithTitle:@"Device is upgrading" Msg:@"Device is upgrading, wait for a moment." btnCancel:@"Ok" Compelete:nil];
        }
      
    }];
    
    [self.view addSubview:self.textView];
    [self.view addSubview:self.progressView];
    [self.view addSubview:self.progressTextLabel];
    
    [self.progressTextLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(30);
        make.leading.equalTo(self.view.mas_leading).offset(40);
        make.trailing.equalTo(self.view.mas_trailing).inset(40);
        make.height.equalTo(@(30));
    }];
    
    [self.progressView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.progressTextLabel);
        make.top.equalTo(self.progressTextLabel.mas_bottom).offset(8);
        make.height.equalTo(@10);
    }];
    
    [self.textView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.progressTextLabel);
        make.top.equalTo(self.progressView.mas_bottom);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
    }];
    
}


- (void) debug:(NSString*)message UILog:(BOOL)uiLog {
    if (uiLog) {
        self.textView.text = [self.textView.text stringByAppendingString:[NSString stringWithFormat:@"\n%@", message]];
        [self.textView scrollRangeToVisible:NSMakeRange([self.textView.text length], 0)];
    }
    DebugNSLog(@"%@", message);
}




-(void)dealloc
{
    
}

#pragma mark --lazy


-(UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]init];
    }
    return _progressView;
}
-(UILabel *)progressTextLabel
{
    if (!_progressTextLabel) {
        _progressTextLabel = [UILabel new];
        _progressTextLabel.textAlignment = NSTextAlignmentCenter;
        _progressTextLabel.textColor = UIColor.darkTextColor;
    }
    return _progressTextLabel;
}

-(UITextView *)textView
{
    if (!_textView) {
        _textView =[UITextView new];
    }
    return _textView;
}

- (NSString*) getErrorMessage:(SPOTA_STATUS_VALUES)status {
    NSString *message;
    
    switch (status) {
        case CAOTAR_SRV_STARTED:
            message = @"Valid memory device has been configured by initiator. No sleep state while in this mode";
            break;
            
        case CAOTAR_CMP_OK:
            message = @"SPOTA process completed successfully.";
            break;
            
        case CAOTAR_SRV_EXIT:
            message = @"Forced exit of SROTAR service.";
            break;
            
        case CAOTAR_CRC_ERR:
            message = @"Overall Patch Data CRC failed";
            break;
            
        case CAOTAR_PATCH_LEN_ERR:
            message = @"Received patch Length not equal to PATCH_LEN characteristic value";
            break;
            
        case CAOTAR_EXT_MEM_WRITE_ERR:
            message = @"External Mem Error (Writing to external device failed)";
            break;
            
        case CAOTAR_INT_MEM_ERR:
            message = @"Internal Mem Error (not enough space for Patch)";
            break;
            
        case CAOTAR_INVAL_MEM_TYPE:
            message = @"Invalid memory device";
            break;
            
        case CAOTAR_APP_ERROR:
            message = @"Application error";
            break;
            
            // SUOTAR application specific error codes
        case CAOTAR_IMG_STARTED:
            message = @"SPOTA started for downloading image (SUOTA application)";
            break;
            
        case CAOTAR_INVAL_IMG_BANK:
            message = @"Invalid image bank";
            break;
            
        case CAOTAR_INVAL_IMG_HDR:
            message = @"Invalid image header";
            break;
            
        case CAOTAR_INVAL_IMG_SIZE:
            message = @"Invalid image size";
            break;
            
        case CAOTAR_INVAL_PRODUCT_HDR:
            message = @"Invalid product header";
            break;
            
        case CAOTAR_SAME_IMG_ERR:
            message = @"Same Image Error";
            break;
            
        case CAOTAR_EXT_MEM_READ_ERR:
            message = @"Failed to read from external memory device";
            break;
            
        default:
            message = @"Unknown error";
            break;
    }
    
    return message;
}

#pragma mark - SROTAProtocal
-(void)caOtaError:(CA_UPD_ERROR)errorCode
{
    NSString *message = [self getErrorMessage:errorCode];
    [self debug:message UILog:(errorCode != CAOTAR_CMP_OK)];
    
    [self showAlertWarningWithTitle:@"Error" Msg:message btnCancel:@"Ok" Compelete:nil];
}

-(void)caOtaFinish:(BOOL)isSuccessful {
    self.isFInish = YES;
    WEAK_SELF
    if (isSuccessful) {
        
        [self showAlertWarningWithTitle:@"Device has been updated" Msg:@"Device has been updated successfully!" btnOk:nil OkBLk:nil CancelBtn:@"OK" CancelBlk:^{
            STRONG_SELF
            [strongSelf.navigationController popToRootViewControllerAnimated:YES];
            
        } Compelete:nil];
    } else {
        [self showAlertWarningWithTitle:@"Device update failed" Msg:@"Device has been updated failed!" btnOk:nil OkBLk:nil CancelBtn:@"OK" CancelBlk:^{
            STRONG_SELF
            [strongSelf.navigationController popToRootViewControllerAnimated:YES];
            
        } Compelete:nil];
    }
  
    
}

-(void)caOtaUpdateProgress:(float)progress
{
    [self.progressView setProgress:progress];
    [self.progressTextLabel setText:[NSString stringWithFormat:@"%d%%", (int)(100 * progress)]];
}

@end
